package com.example.demo.config;


import com.example.demo.common.JsonResult;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 统一返回格式的保底措施, 防止忘记使用 JsonResult 进行返回
 * 在方法返回前调用, 检测数据格式是否是 JsonResult
 * 若不是, 则将数据封装为 JsonResult 进行返回
 */
@ControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice {

    @Autowired
    private ObjectMapper objectMapper;

    /**
     *  该方法返回 true 表示要调用 beforeBodyWrite 进行数据检测
     */
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    /**
     * 检测返回的数据
     */
    @SneakyThrows
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (body instanceof JsonResult) {
            return body;
        }
        if (body instanceof String) {
            // String 要特殊处理, String 在这里自动转为 Json 格式会出问题, 这里要手动转为 Json字符串
            return objectMapper.writeValueAsString(JsonResult.success(body));
        }
        return JsonResult.success(body);
    }
}
